const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
const maxPos = chars.length
const randomString = (len = 32) => {
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

function stringToJson(jsonString) {
  let result = null
  if (jsonString) {
    if (typeof jsonString === 'string') {
      try {
        result = JSON.parse(jsonString)
      } catch (e) {
        console && console.log('stringToJson', e)
      }
    } else if (typeof jsonString === 'object') {
      result = jsonString
    }
  }
  return result
}

/**
 * 合并多个 CSS 类名为一个字符串
 * @param values - 可以是字符串、数组、对象或其他值的组合
 * @returns 合并后的类名字符串,以空格分隔
 * @example
 * ```ts
 * cx('foo', 'bar') // => 'foo bar'
 * cx('foo', { bar: true }) // => 'foo bar'
 * cx(['foo', 'bar']) // => 'foo bar'
 * ```
 */
function cx(...values) {
  const set = new Set()
  function append(value) {
    if (!value || value === true || typeof value === 'number') return
    else if (typeof value === 'string') {
      const classes = value.trim().split(/\s+/)
      for (const cls of classes) if (cls) set.add(cls)
    } else if (Array.isArray(value)) for (const item of value) append(item)
    else for (const [key, val] of Object.entries(value)) if (val) set.add(key)
  }
  for (const value of values) append(value)
  return [...set].join(' ')
}

export { cx, randomString, stringToJson }
